<template>
  <div>
     
    <div class="button-group-container">
      <ActionButtonGroup        
        :show-add="hasPermission('Add')"  
        :show-edit="hasPermission('edit')"  
        :show-delete="hasPermission('delete')" 
        :disabled-add="false"
        :disabled-edit="disabledEdit"
        :disabled-delete="disabledDelete"  
        @add="handleAdd"
        @edit="handleEdit"
        @delete="handleDelete"
        @search="handleSearch"
      />
    </div>
        <!-- 表格 -->
    <CustomTable
      :tableColumns="tableColumns"
      :tableData="tableData"
      v-model:page="pagerConfig"    
      :showSelection="true"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @row-dblclick="handleRowDbClick"
      :row-class-name="myRowClass"  
      height="700" 
    />
    
    <el-dialog
      v-model="formModel"
      :title="formTitle"
      width="80%"
      top="5vh"      
      :before-close="handleClose"
      fullscreen
    >
      <FormComponent
        ref="formComponentRef"
        :fields="fields"
        :data="formData"
        @update:data="handleFormDataUpdate"
      ></FormComponent>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">{{ $t('btn.cancel') }}</el-button>
          <el-button type="primary" @click="handleSave">{{ $t('btn.save') }}</el-button>
        </span>
      </template>
    </el-dialog>

<DynamicSearchDrawer
  v-model="SearchModel"
  v-model:data="searchFormData"
  :fields="searchFields"
  direction="ltr"
  size="420px"
  append-to-body
  destroy-on-close
  @open="onSearchOpen"
  @search="handleQuery"
/>

  </div>
</template>

<script lang="ts" setup>
/* ---------- 系统 ---------- */
import { ref,onMounted,computed,watch } from 'vue';
/* ---------- 子组件 ---------- */
import ActionButtonGroup from "@/components/ActionBtnHdrCont.vue";
import CustomTable from '@/components/ActionVxeGridCont.vue';
import FormComponent from "@/components/ActionFormCont.vue";
import DynamicSearchDrawer from '@/components/ActionSearchCont.vue'
/* ---------- 权限 ---------- */
import { usePermission } from "@/utils/permissionUtils";
/* ---------- 配置文件 ---------- */
import defaultConfig from '@config'; 
import { createQueryParams } from '@/utils';
/* ---------- Form验证 ---------- */
import { buildValidator } from '@/utils/buildValidator';
import { validatorPool } from '@/utils/validatorPool'
/* ---------- API（删除/修改/保存） ---------- */
import { remove,  query, doFormSave,getFields } from '@/utils/apiHelper';
/* ---------- 消息/i18n ---------- */
import { msgError,msg18n } from '@/utils/msg';
import { useI18n } from 'vue-i18n'; // 

/* ---------- 分页---------- */
const currentPage = ref(defaultConfig.tableCurrentPage);// 默认当前页为1
const pageSize = ref(defaultConfig.tablePageSize);// 默认每页显示10条数据
const pageSizes = ref(defaultConfig.tablePageSizes);// 默认分页大小为[10,20,50,100]

/* ---------- 字段、数据配置---------- */
const tableColumns = ref<any[]>([])   // 表字段配置
const fields = ref<any[]>([])    // Form字段配置
const tableData    = ref<any[]>([])   // 表格数据
const formData = ref({}); // Form 数据
const searchFields = ref<any[]>([])  // 查询字段配置
const searchFormData = ref({ status: true })// 查询数据配置
const selectedData = ref([]); // 用于存储Table选中的数据

/* ---------- 权限---------- */
const hasPermission = usePermission();
const formModel = ref(false); //form 窗口显示与关闭
const formComponentRef = ref(null); //栏位校验法则
const disabledEdit= ref(true);      // 编辑按钮禁止
const disabledDelete= ref(true);   // 删除按钮禁止
const SearchModel = ref(false)

/* ---------- 消息与i18n---------- */
let msg='';
const { t } = useI18n(); // 解构出 t 函数
const btnMode = ref<'add' | 'edit'>('add')

/* ---------- 业务属性定义（新的程序原则只修改这里）---------- */
const api_module = 'objectField';
const api_fields='object_field'
const formTitle = computed(() => {
 // console.log('btnMode.value',btnMode.value);
  return btnMode.value === 'add' ? '添加菜单' : '编辑菜单'
});

const props = defineProps({
  parentId: {
    type: [String, Number, null],
    default: null
  },
  data: {
    type: Object,
    default: () => ({})
  }
})

/* ---------- 资料获取---------- */
/* ---------- 资料获取.查询条件---------- */
const queryNoDeleteMark = 0 //查询条件
function getQueryParams(params: Record<string, any> = {}) {
const baseParams = {
    deletion_mark: queryNoDeleteMark,  
    // object_id: props.parentId, 
    ...params,
  };
  
 console.log('getQueryParams',baseParams);
  
  return baseParams;

}
/* ---------- 资料获取.获取Form的数值---------- */
async function fetchDatas(params: Record<string, any> = {},
                          id?: string | number) {
  try {
 
     //const QueryParams=createQueryParams({data: params})
    // const QueryParams = id != null ? undefined : createQueryParams({ data: params });
    const QueryParams = id != null
  ? undefined                      // 单条记录：不需要 QueryParams
  : createQueryParams({
      data: params,                 // 过滤条件
      sort:  ['sort']  // 排序，sort:  ['-sort']
      //page: params.page || 1,       // 页码
      //pageSize: params.pageSize || 20
    });
     const action = id != null ? 'selectById' : 'select';
     const res= await query(api_module,'select',QueryParams,id)
    return res.details ?? []   // 按后端实际字段返回
  } catch {
    msg=t('message.apiException');
    msgError(msg)
    return Promise.reject(new Error(msg))
  }
}


/* ---------- 资料获取.初始化数据加载---------- */
async function loadData() {
  try {
   
    const QueryParams = getQueryParams(searchFormData.value);
    // 并发请求
    /*const [fieldRes] = await Promise.all([
      getFields(api_fields).catch(() => Promise.reject(new Error('字段接口异常')))
    ])
      */
    const fieldRes = await getFields(api_fields).catch(() =>
  Promise.reject(new Error('字段接口异常'))
)

    // 赋值（可选链兜底）    
    tableData.value    = []//tableRes//.details   ?? []
    tableColumns.value      = fieldRes.data?.[api_fields] ?? []  
    //console.log('tableData',tableData.value);        
    searchFields.value = fieldRes.data?.[`${api_fields}_isFilter`] ?? []   

     // 生成表单字段
    fields.value = (fieldRes.data?.[api_fields] || []).map(f => ({
      ...f,
      rules: f.Validation
        ? [{ validator: buildValidator({ ...f.Validation, fieldName: f.label }), trigger: f.Validation.trigger || 'blur' }]
        : undefined
    })) ?? []

  } catch (e: any) {
    msg=t('message.apiException');
    msgError(`${msg}：${e.message}`)
  }
}

/* ---------- 资料获取.重新加载数据---------- */
async function reloadData(params: Record<string, any> = {}) {
  try {
    //console.log('reloadData params',params);
    const QueryParams = getQueryParams(params);
    //console.log('reloadData QueryParams',QueryParams);
    // 并发请求
    console.log('reloadData QueryParams',QueryParams);
    const [tableRes] = await Promise.all([     
     
      fetchDatas(QueryParams)
    ])
    // 赋值（可选链兜底）  
    tableData.value    = tableRes//.details   ?? []
 // console.log('fields',fields.value);
  } catch (e: any) {
    msg=t('message.apiException');
    msgError(`${msg}：${e.message}`)
  }
}

/* ---------- 页面加载初始化--------- */

onMounted(() => {
   loadData(); // 调用 loadData

});
/* ---------- 分页参数 ---------- */
const pagerConfig = ref({
  currentPage: currentPage,
  pageSize: pageSize,
  pageSizes: pageSizes,
  //total: computed(() => filteredData.value.length)
   total: tableData.value.length
})


/* ---------- 新增--------- */
const formInit = ref({
  status: true,
  sort: 10
});

const handleAdd = () => { 

  formData.value = { ...formInit.value }; // 使用展开运算符避免引用问题
    btnMode.value='add';
  formModel.value = true;
};

/* ---------- 修改--------- */
const handleEdit = () => {
 
  if (selectedData.value.length === 1) {
    // 将选中数据赋值给表单数据
        formData.value = { ...selectedData.value[0] };
        btnMode.value='edit';
        formModel.value = true;
      } else if (selectedData.value.length > 1) {
            msg=t('table.selectedMax',{max:1});
        alert(msg);
      } else {
        msg=t('table.noSelected');
        alert(msg);
      }

 
};
/* ---------- 删除--------- */
async function handleDelete() {
  try{  
        await remove(api_module, 'mark', selectedData.value);
        
        await reloadData();
        }
        catch(e:any){
          
        }
  //loadTable();
}
/* ---------- 查询--------- */
const handleSearch= () =>{

  SearchModel.value = true;
}

/* ---------- 编辑Form事件--------- */
/* ---------- 编辑Form事件。Form数据加载更新--------- */
const handleFormDataUpdate = (newData: any) => {
  formData.value = { ...newData };
};
/* ---------- 编辑Form事件.Form数据保存--------- */
const handleSave = async () => {
        const result = await doFormSave({
            module: api_module,
            formData: formData.value,
            formRef: formComponentRef.value?.$refs.formRef,
          });

          if (result.success) {
            if (result.data) formData.value = result.data; // 回写 id 等默认值
            formModel.value = false;
            await reloadData({ object_id: props.parentId });
          }
};
/* ---------- 编辑Form事件.Form取消按钮--------- */
const handleCancel = () => {
  formModel.value = false;
};
/* ---------- 编辑Form事件.Form关闭按钮--------- */
const handleClose = (done: () => void) => {
  formModel.value = false;
  done();
};


/* ---------- 查询事件--------- */
function handleQuery(payload: Record<string, any>) {
  //console.log('查询条件', payload)
  
  reloadData(payload)
  // 调接口
}

/* ---------- 查询事件.数据加载--------- */
function onSearchOpen() {


     console.log('searchFields.value',searchFields.value);

}


/* ---------- 表格操作--------- */
/* ---------- 表格操作.处理选中数据变化--------- */ 
const handleSelectionChange = (selection) => {
  selectedData.value = selection;
  disabledEdit.value = selection.length !== 1;
  disabledDelete.value = selection.length === 0;

};

/* ---------- 表格操作.排序处理函数--------- */ 
const handleSortChange = (sortInfo) => {
  //console.log('排序信息:', sortInfo);
 
};
/* ---------- 表格操作.表格双击事件--------- */ 
const handleRowDbClick = (row, event) => {
    console.log('row double clicked:', row);
  
};
/* ---------- 表格操作.表格式化--------- */ 
function myRowClass({ row, rowIndex }) {   
const status = row.parent_id === '0' ? 'row-success' : 'row-gray-50';
  const stripe = rowIndex % 2 === 0 ? 'row-gray-50' : 'row-white';
  return `${status} ${stripe}`.trim();
}
/* ---------- 增加监听--------- */
/* 监听 parentId 变化 -> 重新加载数据 */
watch(() => props.parentId, (newVal) => {
  if (newVal != null) {
    // 带上父 ID 重新查询
    reloadData({ object_id: newVal })
  } else {
    // 没有父 ID 时清空列表（或保留全部）
    tableData.value = []
  }
}, { immediate: true })   // 首次渲染也执行一次


</script>
